package com.ggh.jinjilive.ui.mall.shopping;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ggh.jinjilive.BaseApplication;
import com.ggh.jinjilive.R;
import com.ggh.jinjilive.databinding.ActivityShopPingCarBinding;
import com.ggh.jinjilive.listener.AddItemOnClickListener;
import com.ggh.jinjilive.listener.AddOnClickListener;
import com.ggh.jinjilive.mobile.mall.goods.GoodsShopSPMobile;
import com.ggh.jinjilive.mobile.mall.shopping.ShopMessageMoblie;
import com.ggh.jinjilive.pagestatus.EmptyCallback;
import com.ggh.jinjilive.pagestatus.LoadingCallback;
import com.ggh.jinjilive.ui.BaseActivity;
import com.ggh.jinjilive.ui.mall.shopping.adapter.ShopingCarAdapter;
import com.ggh.jinjilive.utils.ARouterUtils;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadSir;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.text.DecimalFormat;
import java.util.List;

/**
 * 购物车
 */

@Route(path = ARouterUtils.ShopingCarActivity)
public class ShopingCarActivity extends BaseActivity<ActivityShopPingCarBinding> implements View.OnClickListener{
    //VM
    private ShopPingCarViewModel shopPingCarViewModel;
    private int cid = 0;
    //适配器
    private ShopingCarAdapter shopingCarAdapter;
    @Override
    public void initCreate() {
        super.initCreate();
        ImmersionBar.with(this).init();
        BaseApplication.getInstance().getAppComponent().doInjectionMain(this);
        shopPingCarViewModel = new ViewModelProvider(this,viewModelFactory).get(ShopPingCarViewModel.class);
    }

    @Override
    public void initParam() {
        super.initParam();
        cid = getIntent().getIntExtra("cid", 0);
        shopPingCarViewModel.mCID.set(cid);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_shop_ping_car;
    }



    @Override
    public void initView() {
        super.initView();
        setWhiteActionBarStyle("购物车",true,true);
        //获取状态栏高度
        binding.llSpacing.setPadding(0, BarUtils.getStatusBarHeight(),0,0);

        loadService = LoadSir.getDefault().register(binding.flInformation, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadService.showCallback(LoadingCallback.class);
                //获取购物车的所有商品
                shopPingCarViewModel.isRefresh = true;
                shopPingCarViewModel.cartList();
            }
        });
        loadService.showCallback(LoadingCallback.class);

        //适配器
        shopingCarAdapter = new ShopingCarAdapter();
        //刷新数据
        shopingCarAdapter.setAddItemOnClickListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                List<ShopMessageMoblie> shopMessageMoblieList = (List<ShopMessageMoblie>) mObject;

                if(null != shopMessageMoblieList && shopMessageMoblieList.size() > 0){
                    boolean allSelected = true;
                    for (ShopMessageMoblie shopMessageMoblie : shopMessageMoblieList){
                        if(!shopMessageMoblie.isSelected()){
                            allSelected = false;
                            break;
                        }
                    }
                    binding.cbCheckall.setChecked(allSelected);
                }
                //计算价格
                calculatePrice();
                LogUtils.d("购物车" + new Gson().toJson(shopMessageMoblieList));
            }
        });
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        binding.recyclerView.setAdapter(shopingCarAdapter);

    }

    @Override
    public void initData() {
        super.initData();
        //获取购物车的所有商品
        shopPingCarViewModel.isRefresh = true;
        shopPingCarViewModel.cartList();
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //管理
        binding.managementButton.setOnClickListener(this);
        //立即购买
        binding.ButtonImmediatelyBuy.setOnClickListener(this);
        //获取购物车的所有商品
        shopPingCarViewModel.mShopMessageMoblieList.observe(this, new Observer<List<ShopMessageMoblie>>() {
            @Override
            public void onChanged(List<ShopMessageMoblie> shopMessageMoblieList) {
                if(shopMessageMoblieList.size() > 0) {
                    loadService.showSuccess();
                    shopingCarAdapter.setAdd(shopPingCarViewModel.mShopMessageMoblieList.getValue());
                }else {
                    loadService.showCallback(EmptyCallback.class);
                }
                //计算价格
                calculatePrice();
            }
        });
        //全选
        binding.cbCheckall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(null != shopPingCarViewModel.mShopMessageMoblieList.getValue()){
                    if(binding.cbCheckall.isChecked()){
                        for (int i = 0; i < shopPingCarViewModel.mShopMessageMoblieList.getValue().size(); i++){
                            shopPingCarViewModel.mShopMessageMoblieList.getValue().get(i).setSelected(true);
                            for (int p = 0; p <  shopPingCarViewModel.mShopMessageMoblieList.getValue().get(i).getProduct().size(); p++){
                                shopPingCarViewModel.mShopMessageMoblieList.getValue().get(i).getProduct().get(p).setSelected(true);
                            }
                        }
                    }else {
                        for (int i = 0; i < shopPingCarViewModel.mShopMessageMoblieList.getValue().size(); i++){
                            shopPingCarViewModel.mShopMessageMoblieList.getValue().get(i).setSelected(false);
                            for (int p = 0; p <  shopPingCarViewModel.mShopMessageMoblieList.getValue().get(i).getProduct().size(); p++){
                                shopPingCarViewModel.mShopMessageMoblieList.getValue().get(i).getProduct().get(p).setSelected(false);
                            }
                        }
                    }
                    shopingCarAdapter.setAdd(shopPingCarViewModel.mShopMessageMoblieList.getValue());
                    //计算价格
                    calculatePrice();

                }else {
                    ToastUtils.make().show("数据错误");
                }
            }
        });
    }

    /**
     * 计算价格
     */
    private double calculatePrice(){
        //总价格
        double overall = 0.00;
        if(null != shopPingCarViewModel.mShopMessageMoblieList.getValue()){
            for (int i = 0; i < shopPingCarViewModel.mShopMessageMoblieList.getValue().size(); i++){
                ShopMessageMoblie shopMessageMoblie = shopPingCarViewModel.mShopMessageMoblieList.getValue().get(i);
                for (int p = 0; p < shopMessageMoblie.getProduct().size(); p++){
                    GoodsShopSPMobile goodsShopSPMobile = shopMessageMoblie.getProduct().get(p);
                    if(goodsShopSPMobile.isSelected()){
                        overall = overall + (goodsShopSPMobile.getNum() * goodsShopSPMobile.getProduct_spec_fee());
                    }

                }
            }
        }
        binding.tvPrice.setText("¥"+ decimalFormat.format(overall));
        return overall;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.management_Button://管理
                if(binding.llTotal.getVisibility() == View.VISIBLE){
                    binding.llTotal.setVisibility(View.GONE);
                    binding.ButtonImmediatelyBuy.setText("删除");
                }else {
                    binding.llTotal.setVisibility(View.VISIBLE);
                    binding.ButtonImmediatelyBuy.setText("立即购买");
                }
                break;
            case R.id.Button_immediately_buy://立即购买
                String buyOrDelete = binding.ButtonImmediatelyBuy.getText().toString();
                if(buyOrDelete.equals("立即购买")){
                    if(calculatePrice() > 0){
                        ARouter.getInstance().build(ARouterUtils.ShoppingCarAffirmActivity)
                                .withString("shopping",new Gson().toJson(shopPingCarViewModel.mShopMessageMoblieList.getValue()))
                                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                .navigation();
                    }else {
                        ToastUtils.make().show("你还没有选择宝贝哦!");
                    }
                }else if(buyOrDelete.equals("删除")){
                    if(!TextUtils.isEmpty(deleteGoods())){
                        shopPingCarViewModel.delCart(deleteGoods());
                    }else {
                        ToastUtils.make().show("你还没有选择宝贝哦!");
                    }
                }
                break;
        }
    }

    /**
     * 删除商品
     */
    private String deleteGoods(){
        String deleteList = "";
        if(null != shopPingCarViewModel.mShopMessageMoblieList.getValue()){
            for (int i = 0; i < shopPingCarViewModel.mShopMessageMoblieList.getValue().size(); i++){
                ShopMessageMoblie shopMessageMoblie = shopPingCarViewModel.mShopMessageMoblieList.getValue().get(i);
                for (int p = 0; p < shopMessageMoblie.getProduct().size(); p++){
                    GoodsShopSPMobile goodsShopSPMobile = shopMessageMoblie.getProduct().get(p);
                    if(goodsShopSPMobile.isSelected()){
                        if(TextUtils.isEmpty(deleteList)){
                            deleteList = goodsShopSPMobile.getId() + "";
                        }else {
                            deleteList = deleteList + "," + goodsShopSPMobile.getId();
                        }
                    }

                }
            }
        }
        return deleteList;
    }

}
